package com.zj.leetcode.medium.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @program: algorithm
 * @description: 二叉树的层序遍历 II
 * 107 binary-tree-level-order-traversal-ii
 * @author: Zhang Bo
 * @create: 2022-06-17 10:33:47
 **/
public class BinaryTreeLevelOrderTraversalIi {
    public static void main(String[] args) {
        Solution solution = new BinaryTreeLevelOrderTraversalIi().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if (root == null) {
                return res;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);


            while (queue.size() != 0) {
                List<Integer> list = new ArrayList<>();
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode poll = queue.poll();
                    if (poll != null) {
                        list.add(poll.val);
                        if (poll.left != null) {
                            queue.add(poll.left);
                        }
                        if (poll.right != null) {
                            queue.add(poll.right);
                        }
                    }
                }
                res.add(0, list);
            }

            return res;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
